<template>
    <div>
        <div class="w-form-header" style="min-height:26px">
            <div class="header" v-if="!pageLoading">
                <div class="title-box" style="flex: 1;">
                    <span class="title">款式资讯</span>
                </div>
                <div class="title-box">
                    <span class="status">{{
                        formData.status == "1" ? "已確認" : "草稿"
                    }}</span>
                </div>
            </div>
        </div>
        <div class="admin-content">
            <div class="gva-form-box">
                <el-collapse v-model="activeNames" accordion style="border: none">
                    <el-collapse-item name="1">
                        <template #title>
                            <div
                                class="w-form-box"
                                style="
                                    margin: 0;
                                    flex: 1;
                                    display: flex;
                                    justify-content: space-between;
                                "
                            >
                                <div
                                    class="list-header"
                                    style="margin-bottom: 0"
                                >
                                    基本信息
                                </div>
                                <div
                                    style="margin-right: 10px; font-size: 14px"
                                >
                                    {{ activeNames == 1 ? "收起" : "展开" }}
                                </div>
                            </div>
                        </template>
                        <van-cell-group>
                            <van-cell 
                                v-for="(item, key) in detailFormColumns"
                                :title="item.label" 
                                :value="formData[item.prop] ? (item.formatter ? item.formatter(formData[item.prop], formData) : formData[item.prop]) : '暂无'" 
                            />
                        </van-cell-group>
                    </el-collapse-item>
                </el-collapse>
            </div>
            <div class="gva-form-box">
                <div class="w-form-box">
                    <div class="list-header">计划日期</div>
                    <div>
                        <PlansData
                            ref="PlansDataRef"
                            :isEditing="isEditing"
                            :formData="formData"
                        />
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>

<script setup>
import {
    findProductStyles,
   } from "@/api/plmProductStyles";
import { findSbuProjects } from "@/api/plmSbuProjects";
import { findSbuData } from "@/api/confSbuData";

// 全量引入格式化工具 请按需保留
import { formatDate } from "@/utils/format";
import PlansData from "./PlansData.vue";

const PlansDataRef = ref();

defineOptions({
    name: "ProductStyleDetail",
});

// 自动获取字典
import { useDict } from "@/utils/dictionary.js";
import { useRoute, useRouter } from "vue-router";
import { ref, reactive, onMounted, computed, watchEffect } from "vue";
import { useI18n } from "vue-i18n";

const { t: il8n } = useI18n();

const route = useRoute();
const router = useRouter();

const activeNames = ref("1");
const formData = ref({
    frameMaterial: "",
});

// 字典列表
const dictOptions = ref({
    establishOrder: [], //開辦順序
    glassFrameCate: [], //镜架类别
    drawer: [], // 绘图
    frameCate: [], // 款式資訊-架類
    styleCate: [], // 款式資訊-類別
    costAccountCate: [], //成本核算分類
    frameMaterials: [], //镜架材质
    productGender: [], //款式資訊-性別
    splenicHeadIncisionPosition: [], //脾頭切口位
    hingeType: [], //鉸鏈類別
    businessCate: [], //業務類別
    issuanceMonth: [], //業務月
    issuanceYear: [], //業務年
    transferOrder: [], // 转单
});
const peLeaderOptions = ref([]); // 工程师组长列表
const designerOptions = ref([]); // 设计师列表

const oldFrameMaterial = ref(""); // 旧镜架材质
const oldLocalStyleNum = ref(""); // 旧本厂款号
const oldLocalStyleNumObj = ref({}); // 旧本厂款号列表

const isModifyFrameMaterials = ref(""); // 旧本厂款号列表

const projectPlans = ref([]);

const isEditing = ref(false);
const pageLoading = ref(true);

const detailFormColumns = ref([]);

watchEffect(() => {
  //   基本资料 columns
  const newDetailFormColumns = [
    {
      label: il8n("kuanshibianhao1.label"),
      prop: "styleNum",
    },
    {
      label: il8n("benchangkuanhao.label"),
      prop: "localStyleNum",
    },
    {
      label: il8n("kaibanshunxu.label"),
      prop: "establishOrder",
    },
    {
      label: "创建人",
      prop: "createUser",
    },
    {
      label: il8n("SBU.label"),
      prop: "sbuNum",
    },
    {
      label: il8n("jingjiacaizhi.label"),
      prop: "frameMaterial",
    },
    {
      label: il8n("huitu.label"),
      prop: "drawer",
    },
    {
      label: "创建时间",
      prop: "CreatedAt",
      needformatter: true,
      formatter: (CreatedAt) => formatDate(CreatedAt),
    },
    {
      label: il8n("kehubianhao.label"),
      prop: "cumstomerNum",
    },
    {
      label: il8n("jingjialeibie.label"),
      prop: "glassFrameCate",
    },
    {
      label: il8n("gongchengshizuzhang.label"),
      prop: "peLeader",
    },
    {
      label: "更新人",
      prop: "updateUser",
    },
    {
      label: il8n("kehukuanhao.label"),
      prop: "customerStyleNum",
    },
    {
      label: il8n("yewuleibie.label"),
      prop: "businessCate",
    },
    {
      label: il8n("shejishi.label"),
      prop: "designer",
    },
    {
      label: "更新时间",
      prop: "UpdatedAt",
      needformatter: true,
      formatter: (UpdatedAt) => formatDate(UpdatedAt),
    },
    {
      label: il8n("kehupinpai.label"),
      prop: "customerBrand",
    },
    {
      label: il8n("xilie.label"),
      prop: "series",
    },
    {
      label: "生产报价",
      prop: "transferOrderRange",
    },
    {
      label: "性别",
      prop: "gender",
    },
  ];
  detailFormColumns.value = newDetailFormColumns;
  
});

// 初始化方法
const init = async () => {
    // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
    const { query: { styleNum } } = route;
   
    oldFrameMaterial.value = null;
    oldLocalStyleNum.value = null;
    oldLocalStyleNumObj.value = {};
    pageLoading.value = true;

    findProductStyles({ styleNum })
        .then(async (res) => {
            pageLoading.value = false;
            if (res.code === 0) {
                formData.value = res.data.reproductStyles;
                console.log('=======>',res.data.reproductStyles)
                
                if (!!formData.value.localStyleNum) {
                    oldFrameMaterial.value = formData.value.frameMaterial;
                    oldLocalStyleNum.value = formData.value.localStyleNum;
                    oldLocalStyleNumObj.value[
                        formData.value.frameMaterial
                    ] = formData.value.localStyleNum;
                }
                
                findSbuDataFun(formData.value.sbuNum);
                
                PlansDataRef.value.updateValue(formData.value.projectPlans);
                dataNumChange();
                if (res.data.reproductStyles.status == 0) {
                    const projectsRes = await findSbuProjects({
                        projectNum: res.data.reproductStyles.projectNum,
                    });
                    const { sbuName, customerName, brandName } =
                        projectsRes.data.resbuProjects;
                    if (sbuName) {
                        formData.value.sbuNum = sbuName;
                    }
                    if (customerName) {
                        formData.value.cumstomerNum = customerName;
                    }
                    if (brandName) {
                        formData.value.customerBrand = brandName;
                    }
                }

                isModifyFrameMaterials.value =
                    res.data.isModifyFrameMaterials;
            }
        })
        .catch((err) => {
            pageLoading.value = false;
        });
    
};

init();

// 获取sbu信息
const findSbuDataFun = (sbuNum) => {
    findSbuData({ sbuName: sbuNum }).then((res) => {
        const tempMembers = res.data.resbuData.members;
        if (tempMembers) {
            designerOptions.value = tempMembers;
            peLeaderOptions.value = tempMembers;
            const tempDesigner = tempMembers.filter((item) => item.value == formData.value.designer);
            const tempPeLeader = tempMembers.filter((item) => item.value == formData.value.peLeader);
            if (tempDesigner.length > 0) {
                formData.value.designer = `${tempDesigner[0].nickName}(${tempDesigner[0].userName})`;
            }
            if (tempPeLeader.length > 0) {
                formData.value.peLeader = `${tempDesigner[0].nickName}(${tempDesigner[0].userName})`;
            }
        }
    });
};

const sumDay = (dateStr, days) => {
    const date = new Date(dateStr);
    date.setDate(date.getDate() + days);
    return date.toISOString();
};

// 时间改变plannedStartDate,plannedCompletionDate
const dataNumChange = () => {
    projectPlans.value.forEach((item, index) => {
        if (index != 0) {
            if (item.related == "1") {
                let data1 = sumDay(
                    projectPlans.value[0].plannedCompletionDate,
                    1
                );
                item["plannedStartDate"] = data1;
                let data2 = sumDay(data1, +item.planCycle);
                item["plannedCompletionDate"] = data2;
            } else {
                if (item.nodeIndex != item.related) {
                    let i = projectPlans.value.findIndex((d) => {
                        return item.related == d.nodeIndex;
                    });
                    let data1 = projectPlans.value[i].plannedCompletionDate;
                    item["plannedStartDate"] = data1;
                    let data2 = sumDay(data1, +item.planCycle);
                    item["plannedCompletionDate"] = data2;
                }
            }
        }
    });
};

// 开办顺序改变
const establishOrderChange = () => {
    PlansDataRef.value.establishOrderChange();
};
// 绘图改变
const drawerChange = () => {
    PlansDataRef.value.drawerChange();
};

onMounted(async () => {
    const dict = await useDict(
        "establishOrder",
        "glassFrameCate",
        "drawer",
        "frameCate",
        "styleCate",
        "costAccountCate",
        "frameMaterials",
        "productGender",
        "splenicHeadIncisionPosition",
        "hingeType",
        "businessCate",
        "issuanceYear",
        "issuanceMonth",
        "transferOrder"
    );
    dictOptions.value = Object.assign(dictOptions.value, dict);
});
</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");

.gva-form-box {
    :deep(.my-label) {
        width: 9%;
    }

    :deep(.my-content) {
        width: 16%;
    }
}

.title-box {
    display: flex;
    align-items: center;

    .title {
        font-size: 13px;
        color: rgba(173, 173, 173, 1);
    }
}

:deep(.el-collapse-item__content) {
    padding-bottom: 0;
}
</style>
